package cn.wit.summit.chwan.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.SearchAdapter;
import cn.wit.summit.chwan.adapters.SearchAutoAdapter;
import cn.wit.summit.chwan.adapters.SearchHotAdapter;
import cn.wit.summit.chwan.adapters.SearchResultAdapter;
import cn.wit.summit.chwan.interfaces.AdapterInterface;
import cn.wit.summit.chwan.interfaces.MyScrollListener;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.db.HistorySearchTable;
import cn.wit.summit.chwan.models.dbmanager.HistorySeachManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.models.response.SearchAutoResponse;
import cn.wit.summit.chwan.models.response.SearchResultResponse;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.ClearEditText;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import retrofit2.Retrofit;

/**
 * 搜索
 * Created by Alan on 2018/4/17.
 */

public class SearchActivity extends MyActivity implements AdapterInterface, View.OnClickListener {

    @Bind(R.id.clearEditText)
    ClearEditText clearEditText;
    @Bind(R.id.searchListView)
    ListView searchListView;
    @Bind(R.id.autoListView)
    ListView autoListView;
    @Bind(R.id.keyWordTv)
    TextView keyWordTv;
    @Bind(R.id.emptyRootLl)
    LinearLayout emptyRootLl;
    @Bind(R.id.mPtrFrameSearchRl)
    RelativeLayout mPtrFrameSearchRl;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private SearchHotAdapter mSearchHotAdapter;

    private SearchAutoAdapter mSearchAutoAdapter;

    private int tagId = 0;
    private int pn = 1;
    private SearchResultAdapter mSearchResultAdapter;
    private List<SearchResultAdapter.ViewBean> viewBeans = new ArrayList<>();
    private List<SearchResultAdapter.ViewBean> viewTopBeans = new ArrayList<>();

    private boolean isfromKeyWord = false;

    private LinearLayoutManager layoutManager;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        hideTitleBar();
        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        initView();
//        initHotList();
        initHistorySearch();
        initAutoList();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showSoftInput(clearEditText);
            }
        }, 400);
    }

    private HistorySeachManager mHistorySeachManager = null;
    private List<HistorySearchTable> searchList = new ArrayList<>();
    private View viewBottom = null;
    private LinearLayout keyWordDetaleLl;
    private SearchAdapter mSearchAdapter;

    private void initHistorySearch() {
        if (mHistorySeachManager == null)
            mHistorySeachManager = HistorySeachManager.getInstance();

        if (searchList.size() != 0)
            searchListView.removeFooterView(viewBottom);

        searchList = mHistorySeachManager.getAllSearch();
        viewBottom = LayoutInflater.from(mContext).inflate(R.layout.bottom_keyword_view, null);
        keyWordDetaleLl = viewBottom.findViewById(R.id.keyWordDetaleLl);
        keyWordDetaleLl.setOnClickListener(this);
        mSearchAdapter = new SearchAdapter(mContext, searchList, this);
        if (searchList.size() != 0)
            searchListView.addFooterView(viewBottom);
        searchListView.setAdapter(mSearchAdapter);
        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isfromKeyWord = true;
                clearEditText.setText("");
                clearEditText.setText(mSearchAdapter.getItem(position).getKeyWord());
                pn = 1;
                tagId = 0;
                toSearch(mSearchAdapter.getItem(position).getKeyWord());
            }
        });
    }

    private void initAutoList() {
        mSearchAutoAdapter = new SearchAutoAdapter(mContext);
        autoListView.setAdapter(mSearchAutoAdapter);
        autoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isfromKeyWord = true;
                String key = mSearchAutoAdapter.getItem(position).getGame_name();
                clearEditText.setText("");
                clearEditText.setText(key);
                pn = 1;
                tagId = 0;
                toSearch(key);
            }
        });
    }

    private void initHotList() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            list.add("第" + (i + 1) + "个");
        }
        mSearchHotAdapter = new SearchHotAdapter(mContext, list);
//        hotListView.setAdapter(mSearchHotAdapter);
//        hotListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                isfromKeyWord = true;
//                String key = mSearchHotAdapter.getItem(position);
//                clearEditText.setText(key);
//                toSearch(key);
//            }
//        });
    }

    private void initView() {
        clearEditText.setOnEditorActionListener(EnterListenter);
        clearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                LogUtils.e("clearEditText>>beforeTextChanged>>start:"+start+",count:"+count+",after:"+after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                LogUtils.e("clearEditText>>beforeTextChanged>>start:"+start+",count:"+count+",before:"+before);
//                if (start==0 && count>0) {
//                    clearEditText.setSelection(count);
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
//                LogUtils.e("clearEditText>>beforeTextChanged>>str:"+str.length());
                if (str.isEmpty()) {
//                    hotListView.setVisibility(View.VISIBLE);
                    searchListView.setVisibility(View.VISIBLE);
                    autoListView.setVisibility(View.GONE);
                    mPtrFrameSearchRl.setVisibility(View.GONE);
                    initHistorySearch();
                } else {
                    if (isfromKeyWord) {
                        isfromKeyWord = false;
                        return;
                    }
//                    hotListView.setVisibility(View.GONE);
                    searchListView.setVisibility(View.GONE);
                    autoListView.setVisibility(View.VISIBLE);
                    mPtrFrameSearchRl.setVisibility(View.GONE);
                    autoSearch(str);
                }
            }
        });

        mSearchResultAdapter = new SearchResultAdapter(this, viewBeans, this);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mSearchResultAdapter);
        recyclerView.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                toSearch(clearEditText.getText().toString().trim(), false);
            }
        });

    }

    @OnClick({R.id.searchBarCancelTx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.searchBarCancelTx:
                finish();
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
        }
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {
        /**
         * 参数说明
         * @param v 被监听的对象
         * @param actionId  动作标识符,如果值等于EditorInfo.IME_NULL，则回车键被按下。
         * @param event    如果由输入键触发，这是事件；否则，这是空的(比如非输入键触发是空的)。
         * @return 返回你的动作
         */
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                pn = 1;
                tagId = 0;
                toSearch(clearEditText.getText().toString().trim());
            }
            return false;
        }
    };

    private void autoSearch(String keyWorld) {
        mSearchAutoAdapter.clearData();
        api.getAutoSearch(keyWorld).enqueue(new MyCallback<ResponseBase<List<SearchAutoResponse>>>() {
            @Override
            public void onSuccess(ResponseBase<List<SearchAutoResponse>> model) {
                List<SearchAutoResponse> data = model.getData_info();
                showAutoList(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                //hotListView.setVisibility(View.GONE);
                searchListView.setVisibility(View.GONE);
                mPtrFrameSearchRl.setVisibility(View.GONE);
                autoListView.setVisibility(View.VISIBLE);

                mSearchAutoAdapter.clearData();
            }
        });
    }

    private void showAutoList(List<SearchAutoResponse> data) {
//        hotListView.setVisibility(View.GONE);
        searchListView.setVisibility(View.GONE);
        mPtrFrameSearchRl.setVisibility(View.GONE);
        if (data != null && data.size() > 0) {
            mSearchAutoAdapter.setmList(data);
            autoListView.setVisibility(View.VISIBLE);
        } else {
            autoListView.setVisibility(View.GONE);
        }
    }

    private void toSearch(String keyWorld) {
        toSearch(keyWorld, false);
    }

    private void toSearch(String keyWorld, final boolean isRefresh) {
        refreshLayout.setEnableLoadMore(true);
        if (StringUtils.isEmpty(keyWorld)) {
            showToast(getResources().getString(R.string.toast_search_empty_str));
            return;
        }
        if (pn==1) {
            showLoading(getResources().getString(R.string.searching));
            refreshLayout.setNoMoreData(false);
            if (tagId==0)
                mSearchResultAdapter.setViewpageIndex(0);
        }
        clearEditText.clearFocus();
        hideSoftInput(clearEditText);
        mHistorySeachManager.insertSearch(keyWorld);
        api.getSearch(retrofitManager.searchRequest(keyWorld, pn, tagId)).enqueue(new MyCallback<ResponseBase<SearchResultResponse>>() {
            @Override
            public void onSuccess(ResponseBase<SearchResultResponse> model) {
                SearchResultResponse data = model.getData_info();
                showResultList(data, isRefresh);
            }

            @Override
            public void onFailure(int code, String msg) {
                if (!isRefresh) {
                    cancelLoading();
                }
                showToast(msg);

                if (pn==1 && viewBeans.size()==0) {
//                    hotListView.setVisibility(View.GONE);
                    searchListView.setVisibility(View.GONE);
                    mPtrFrameSearchRl.setVisibility(View.VISIBLE);
                    autoListView.setVisibility(View.GONE);
                    emptyRootLl.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }
                refreshLayout.finishLoadMore(false);
            }
        });
    }

    private void showResultList(SearchResultResponse data, boolean isRefresh) {
//        hotListView.setVisibility(View.GONE);
        searchListView.setVisibility(View.GONE);
        mPtrFrameSearchRl.setVisibility(View.VISIBLE);
        autoListView.setVisibility(View.GONE);

        if (pn==1) {
            viewBeans.clear();
            mSearchResultAdapter.clearTempData();
        }

        if (data == null) {
            if (pn==1) {
                JumpBaseBean jumpBaseBean = new JumpBaseBean();
                jumpBaseBean.setJump_title("许愿池");
                jumpBaseBean.setJump_sub_title("说出你想要的游戏，让其他小伙伴24小时内帮你找到");
                JumpBaseBean.JumpInfoBean jump_info = new JumpBaseBean.JumpInfoBean();
                jump_info.setJump_link_type("3");
                jump_info.setJump_type("17");
                jump_info.setJump_link_type_val("17");
                jumpBaseBean.setJump_info(jump_info);
                SearchResultAdapter.ViewBean adView = new SearchResultAdapter.ViewBean(
                        SearchResultAdapter.ViewType.TYPE_AD, jumpBaseBean);
                viewBeans.add(adView);
                refreshLayout.setEnableLoadMore(false);
//                emptyRootLl.setVisibility(View.VISIBLE);
//                refreshLayout.setVisibility(View.GONE);
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            emptyRootLl.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);

            if (data.getTag_info() != null) {
                SearchResultAdapter.ViewBean viewBean = new SearchResultAdapter.ViewBean(
                        SearchResultAdapter.ViewType.TYPE_TAB, data.getTag_info());
                viewBeans.add(viewBean);
            }

            JumpBaseBean jumpBaseBean = data.getAd_info();
            if (pn == 1 && viewBeans.size()<=2 && jumpBaseBean!=null && jumpBaseBean.getJump_ad_switch()==1 ) {
                SearchResultAdapter.ViewBean adView = new SearchResultAdapter.ViewBean(
                        SearchResultAdapter.ViewType.TYPE_AD, data.getAd_info());
                viewBeans.add(adView);
            }

            if (data.getList() != null && data.getList().size() > 0) {
                for (int i = 0; i < data.getList().size(); i++) {
                    if (i!=0) {
                        SearchResultAdapter.ViewBean line = new SearchResultAdapter.ViewBean(
                                SearchResultAdapter.ViewType.TYPE_LINE_SMALL, null);
                        viewBeans.add(line);
                    }
                    GameListBaseBean temp = data.getList().get(i);
                    SearchResultAdapter.ViewBean viewBean = new SearchResultAdapter.ViewBean(
                            SearchResultAdapter.ViewType.TYPE_LIST, temp);
                    viewBeans.add(viewBean);
                }

                refreshLayout.finishLoadMore();
                pn += 1;
            } else {
//                if (pn==1) {
//                    JumpBaseBean jump = new JumpBaseBean();
//                    jump.setJump_title("许愿池");
//                    jump.setJump_sub_title("说出你想要的游戏，让其他小伙伴24小时内帮你找到");
//                    JumpBaseBean.JumpInfoBean jump_info = new JumpBaseBean.JumpInfoBean();
//                    jump_info.setJump_link_type("3");
//                    jump_info.setJump_type("17");
//                    jump_info.setJump_link_type_val("17");
//                    jump.setJump_info(jump_info);
//                    SearchResultAdapter.ViewBean adView = new SearchResultAdapter.ViewBean(
//                            SearchResultAdapter.ViewType.TYPE_AD, jump);
//                    viewBeans.add(adView);
//                    refreshLayout.setEnableLoadMore(false);
//                }
                if (pn == 1 && viewBeans.size()<=2) {
                    SearchResultAdapter.ViewBean viewBean = new SearchResultAdapter.ViewBean(
                            SearchResultAdapter.ViewType.TYPE_NULL, null);
                    viewBeans.add(viewBean);
                }

                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        }

        if (isRefresh)
            refreshLayout.finishRefresh();
        else
            cancelLoading();
        mSearchResultAdapter.notifyDataSetChanged();
    }

    @Override
    public void onAdapterItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.itemSearchIv:
            case R.id.xiyuanBt:
                startActivity(new Intent(mContext, TreviFountainActivity.class));
                break;
            case R.id.itemDeleteIv:
                try {
                    mHistorySeachManager.deleteSearch(mSearchAdapter.getItem(position).getKeyWord());
                    mSearchAdapter.deleteItem(position);
                    if (mSearchAdapter.getCount()==0) {
                        searchListView.removeFooterView(viewBottom);
                    }
                } catch (Exception e) {
                }
                break;
            default:
                pn = 1;
                tagId = position;
                toSearch(clearEditText.getText().toString().trim());
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.keyWordDetaleLl:
                mHistorySeachManager.deleteSearchAll();
                reGetSearchKey();
                break;
        }
    }

    private void reGetSearchKey() {
        if (searchList.size() != 0) {
            searchListView.removeFooterView(viewBottom);
            searchList.clear();
        }
        searchList = mHistorySeachManager.getAllSearch();
        if (searchList.size() != 0)
            searchListView.addFooterView(viewBottom);
        mSearchAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = mSearchResultAdapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = mSearchResultAdapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
    }
}
